import router from "../router";
import useStore from "../store";
import TagModel from '../class/TagModel'
import TreeModel from '../class/TreeModel'
import UserInfo from "../class/UserInfo";
import { getTreeMenu } from '../http'
import jwtDecode from "jwt-decode";
//选择菜单时添加tag
export const handleSelect = (index: string) => {
    // if (index == "/") return;
    let name = router.getRoutes().filter(i => i.path == index)[0].name as string
    let model: TagModel = {
        Name: name,
        Index: index,
        Checked: true
    }
    let tags: Array<TagModel> = useStore().tags
    if (tags.find(f => f.Index == index) == undefined) {
        tags.push(model)
        useStore().$patch({ tags: tags })
    }
    tagClick(index, name)
}

//点击tag 设置checked更新store跳转路由
export const tagClick = (index: string, name: string) => {
    if (index == "/" && (name == undefined || name == null)) return;
    let curr = useStore().tags
    curr.forEach(p => {
        if (p.Index == index) {
            p.Checked = true
        } else {
            p.Checked = false
        }
    })
    useStore().$patch({ tags: curr })
    router.push({ path: index })
}

//递归路由，返回list
export const RecursiveRoutes = (tree: Array<TreeModel>) => {
    let list: Array<TreeModel> = []
    for (let i = 0; i < tree.length; i++) {
        let node = tree[i]
        if (node.children) {
            let childrenList = RecursiveRoutes(node.children)
            list = list.concat(childrenList)
        }
        if (node.FilePath == "") {
            continue
        }
        list.push({
            Id: node.Id,
            Index: node.Index,
            MenuName: node.MenuName,
            FilePath: node.FilePath,
            Order: node.Order,
            Icon: node.Icon,
            IsEnable: node.IsEnable,
            ParentId: node.ParentId,
            children: node.children == undefined || node.children == null ? [] : node.children
        })
    }
    return list
}

//设置用户动态路由，更新全局状态
export const SettingUserRouter = async () => {
    //读取所有节点下的文件
    const m = import.meta.glob(['../views/*/*.vue', '../views/*/*/*.vue', '../views/*/*/*/*.vue', '../views/*/*/*/*/*.vue'])
    let localArrary: any[] = []
    for (var i in m) {
        localArrary.push({ filepath: i, component: m[i] })
    }

    //对接权限菜单数据
    const obj = {
        Name: "",
        Index: "",
        FilePath: "",
        ParentId: "",
        Description: ""
    }
    const tree: Array<TreeModel> = (await getTreeMenu(obj)) as any as Array<TreeModel>
    //递归路由，将tree转换list
    const list: Array<TreeModel> = RecursiveRoutes(tree)
    list.forEach(f => {
        var menuInfo = localArrary.find(d => d.filepath.toLowerCase().indexOf(f.FilePath.toLowerCase()) >= 0)
        if (menuInfo) {
            //动态添加luyou
            router.addRoute("admin", {
                name: f.MenuName,
                path: f.Index,
                component: menuInfo.component
            })
        }
    })
    //更新全局状态
    useStore().$patch({ UserMenus: tree })
}

//格式化token
export const FormatToken = (token: string) => {
    if (token) {
        return jwtDecode(token) as UserInfo
    } else {
        return null
    }
}

//格式化时间
export const FormatDate = (val: number) => {
    const dt = new Date(val * 1000)
    const y = dt.getFullYear()
    const m = (dt.getMonth() + 1 + '').padStart(2, '0')
    const d = (dt.getDate() + '').padStart(2, '0')
    const hh = (dt.getHours() + '').padStart(2, '0')
    const mm = (dt.getMinutes() + '').padStart(2, '0')
    const ss = (dt.getSeconds() + '').padStart(2, '0')
    return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}

//获取当前时间
export const GetDate = () => {
    const dt = new Date()
    const y = dt.getFullYear()
    const m = (dt.getMonth() + 1 + '').padStart(2, '0')
    const d = (dt.getDate() + '').padStart(2, '0')
    const hh = (dt.getHours() + '').padStart(2, '0')
    const mm = (dt.getMinutes() + '').padStart(2, '0')
    const ss = (dt.getSeconds() + '').padStart(2, '0')
    return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}

//判断token有效期
export const Vaild = (val: number): boolean => {
    if (val) {
        if (FormatDate(val) >= GetDate()) {
            return true
        }
    }
    return false
}